package com.taotao.sso.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.converter.json.MappingJacksonValue;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.taotao.common.pojo.TaotaoResult;
import com.taotao.common.utils.ExceptionUtil;
import com.taotao.sso.service.LoginService;

@Controller
@RequestMapping("/user")
public class LoginController {
	@Autowired
	private LoginService loginService;

	/**
	 * 发布登录服务,返回token
	 * 
	 * @param username
	 * @param password
	 * @param request
	 * @param response
	 * @return
	 * @author: JSJ
	 */
	@ResponseBody
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public TaotaoResult login(String username, String password,
			HttpServletRequest request, HttpServletResponse response) {
		try {
			TaotaoResult result = loginService.login(username, password,
					request, response);
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			return TaotaoResult.build(500, ExceptionUtil.getStackTrace(e));
		}
	}

	/**
	 * 根据token获取用户信息的服务
	 * 
	 * @param token
	 * @param callback
	 * @return
	 * @author: JSJ
	 */
	@ResponseBody
	@RequestMapping("/token/{token}")
	public Object getUserByToken(@PathVariable String token, String callback) {
		try {
			TaotaoResult result = loginService.getUserByToken(token);
			if (StringUtils.isNotBlank(callback)) {
				MappingJacksonValue mappingJacksonValue = new MappingJacksonValue(
						result);
				mappingJacksonValue.setJsonpFunction(callback);
				return mappingJacksonValue;
			}
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			return TaotaoResult.build(500, ExceptionUtil.getStackTrace(e));
		}
	}

	/**
	 * 用户退出登录服务
	 * 
	 * @param token
	 * @param callback
	 * @return
	 * @author: JSJ
	 */
	@ResponseBody
	@RequestMapping("/logout/{token}")
	public Object logout(@PathVariable String token, String callback,
			HttpServletRequest request, HttpServletResponse response) {
		try {
			TaotaoResult result = loginService.logout(token, request, response);
			if (StringUtils.isNotBlank(callback)) {
				MappingJacksonValue mappingJacksonValue = new MappingJacksonValue(
						result);
				mappingJacksonValue.setJsonpFunction(callback);
				return mappingJacksonValue;
			}
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			return TaotaoResult.build(500, ExceptionUtil.getStackTrace(e));
		}
	}
}
